<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/29 0029
 * Time: 下午 5:34
 */
namespace app\wx\controller;
use think\Controller;
use think\Db;
use think\Validate;
use JsSdk\jssdk;
use think\Config;
use JsSdk\wechat;
class Home extends Controller{
    /**
     * 是否需要授权
     * @var type
     */
//    protected $needAuth = false;
    public function _initialize(){//初始化方法
        // session(null);die;
        $appid = 'wx39fa99d95bce2461';
        $this->appid=$appid;
        $appsecret   = '434451589b0205d49e6b8273e7b4b38f';

//        $jssdk       = new jssdk($this->appid, $appsecret);
//
//        $signPackage = $jssdk->GetSignPackage();//获取签名包
//        // dump($signPackage);die;
//        $this->signPackage = $signPackage;
//
//        if ($this->needAuth) {
//
//            // 判断用户是否已登录
//            if (!session('?is_login')) {
//                // 记录用户访问的url
//                $destUrl = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];//就是取得主机名和
//                //预定义服务器变量的一种，所有$_SERVER开头的都叫做预定义服务器变量 REQUEST_URI的作用是取得当前URI，也就是除域名外后面的完整的地址路径
//                //例如。当前页面是http://www.zixueku.com/plus/search.php?kwtype=0&keyword=php&searchtype=titlekeyword
//                //echo $_SERVER["REQUEST_URI"];
//                //结果就为：plus/search.php?kwtype=0&keyword=php&searchtype=titlekeyword
//
//                session('_dest_url', $destUrl);
//
//                $callback = config('url'). '/Login/auth';// callback 是登录之后微信跳转到你的哪个页面
//
//                $state = md5(uniqid())                ;
//                $wechat = new Wechat();
//                $loginUrl = $wechat->getOauthRedirect($callback, $state);//getOauthRedirect($callback,$state,$scope) 获取网页授 oauth跳转地址
//                $this->redirect($loginUrl);
//            }
//
//        }
    }

//    private function checkSignature()	{
//        $signature = $_GET["signature"];
//        $timestamp = $_GET["timestamp"];
//        $nonce = $_GET["nonce"];
//        $token = TOKEN;
//        $tmpArr = array($token, $timestamp, $nonce);
//        sort($tmpArr);
//        $tmpStr = implode( $tmpArr );
//        $tmpStr = sha1( $tmpStr );
//        if( $tmpStr == $signature ){
//            return true;
//        }else{
//            return false;
//        }
//    }

//    private function checkSignature()
//    {
//        // you must define TOKEN by yourself
//        if (!defined("TOKEN")) {
//            throw new Exception('TOKEN is not defined!');
//        }
//
//        $signature = $_GET["signature"];
//        $timestamp = $_GET["timestamp"];
//        $nonce = $_GET["nonce"];
//
//        $token = TOKEN;
//        $tmpArr = array($token, $timestamp, $nonce);
//        // use SORT_STRING rule
//        sort($tmpArr, SORT_STRING);
//        $tmpStr = implode( $tmpArr );
//        $tmpStr = sha1( $tmpStr );
//
//        if( $tmpStr == $signature ){
//            return true;
//        }else{
//            return false;
//        }
//    }

    //生成菜单导航
    public function creatTree()
    {
        $data = array(
            'button' => array(
                array(
                    'name' => '微官网',
                    'url' => 'http://gx.lgfteam.com/wx/index/index',
                    'type' => 'view',
                ),
                array(
                    'name' => '新闻动态',
                    'sub_button' => array(
                        array(
                            'type' => 'view',
                            'name' => '新闻动态',
                            'url' => 'http://gx.lgfteam.com/wx/news/new_list',
                        )
                    ),
                ),
                array(
                    'name' => '账号入口',
                    'sub_button' => array(
                        array(
                            'type' => 'view',
                            'name' => '意见反馈',
                            'url' => 'http://gx.lgfteam.com/wx/fankui/fankui',
                        ), array(
                            'type' => 'view',
                            'name' => '账号注册',
                            'url' => 'http://gx.lgfteam.com/wx/home/zhuce',
                        ), array(
                            'type' => 'view',
                            'name' => '账号登陆',
                            'url' => 'http://gx.lgfteam.com/wx/home/login',
                        )

                    )
                )
            )
        );
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx39fa99d95bce2461&secret=434451589b0205d49e6b8273e7b4b38f";
        $res = json_decode($this->httpGet($url));
        $access_token = $res->access_token;
        $wechat = new Wechat();
        $wechat->createMenu($data, $access_token);
    }

    //登录检测
    public function is_login(){
        if(!session('?user_id')){
            echo "<script>alert('您还没有登录，请登录后操作');window.location.href='http://www.hmzx.com/wx/home/login'</script>";
            exit;
        }
    }

    //收费员登录检测
    public function is_staff_login(){
        if(!session('?staff_id')){
            echo "<script>alert('您还没有登录，请登录后操作');window.location.href='http://www.hmzx.com/wx/shoufei/shoufei_user'</script>";
            exit;
        }
    }

    //绑定检测
    public function is_bind(){
        if(!$this->getUserId()){
            echo "<script>alert('您还没有绑定主卡，请绑定后操作');window.location.href='http://www.hmzx.com/wx/Bangding/bangding'</script>";
            exit;
        }
    }

    //获取用户ID
    public function getUserId(){
        return Db::name('core_user')->where('register_id',session('user_id'))->value('id');
    }

    //注册
    public function zhuce(){
        if($this->request->isPost()){
            $data = input('post.');
            $validate = new Validate([
//                ['code','require','请填写短信验证码'],
                ['password','length:8,12|alphaNum|confirm:password_show','登录密码只能为8-12位|登录密码只能为字母、数字或字母与数字的组合|两次密码不一致'],
                ['password_show','length:8,12|alphaNum|confirm:password','登录密码只能为8-12位|登录密码只能为字母、数字或字母与数字的组合|a两次密码不一致'],
                ['phone','/^1[123456789]\d{9}$/','手机格式错误']
            ]);
            if(!$validate->check($data)){
                return json(array('msg'=>$validate->getError()));
            }
//            if($data['code'] != session('code')){
//                return json(array('msg'=>'验证码不正确，请确认短信验证码'));
//            }
            if($data['password'] != $data['password_show']){
                return json(array('msg'=>'密码核验不正确，请确认两次密码是否一致'));
            }
            session('code',null);
            unset($data['code']);
            $data['username'] = $data['phone'];
            $data['create_time'] = time();
            $data['password'] = md5($data['password']);
            $id = Db::name('core_register')->insertGetId($data);
            session('user_id',$id);
            return json(['code'=>200]);
        }
        return $this->fetch();
    }


    //登录
    public function login(){
        if($this->request->isPost()){
            $data = input('post.');
            if(empty($data['phone']) || empty($data['password'])){
                return json(['msg'=>'账号或密码不能为空']);
            }
            if(!$info = Db::name('core_register')->where(['phone'=>$data['phone'],'password'=>md5($data['password'])])->find()){
                return json(array('msg'=>'账号或密码错误'));
            }else{
                session('user_id',$info['id']);
                return json(200);
            }
        }
        return $this->fetch();
    }

    //忘记密码
    public function find_pass(){
        if($this->request->isPost()){
            $data = input('post.');
            $validate = new Validate([
                ['phone','require','请输入手机号'],
                ['code','require','请输入验证码'],
                ['password','require','请输入密码'],
                ['password_show','require','请输入确认密码'],
            ]);
            if(!$validate->check($data)){
                return json(array('msg'=>$validate->getError()));
            }
            if($data['password'] != $data['password_show']){
                return json(array('msg'=>'两次密码不正确，请重新输入！'));
            }
            if($data['code'] != session('code') || !session('?code')){
                return json(array('msg'=>'验证码不正确，请重新填写'));
            }
            session('code',null);
            Db::name('core_register')->where('phone',$data['phone'])->update(['password' => md5($data['password']),'password_show'=>$data['password_show']]);
            return json(200);
        }
        return $this->fetch();
    }

    //用户名是否已被注册过
    public function getRegisterInfo(){
        if(Db::name('core_register')->where('phone',input('phone'))->find()){
            return json(['msg'=>'此手机号已注册']);
        }
        $this->code();
        return json(200);
    }

    //检测用户名是否存在
    public function checkUserName(){
        if(!Db::name('core_register')->where('username',input('username'))->find()){
            return json(['code'=>500,'msg'=>'用户名不存在']);
        }
        return json(array(['code'=>200]));
    }

    //获取要登录的用户信息
    public function getUserInfo(){
        if(!Db::name('core_register')->where(['phone'=>input('post.phone')])->find()){
            return json(array('msg'=>'账号不存在'));
        }
        $this->code();
        return json(200);
    }

    //收费登录
    public function shoufei_user(){
        if($this->request->isPost()){
            $data = input('post.');
            if(empty($data['username']) || empty($data['password'])){
                return json(['msg'=>'账号或密码不能为空']);
            }
            if(!$info = Db::name('core_staff')->where(['username'=>$data['username'],'password'=>md5($data['password'])])->find()){
                return json(array('msg'=>'账号或密码错误'));
            }else{
                session('staff_id',$info['id']);
                return json(200);
            }
        }
        $this->view->content = Db::name('config')->where('name','notice_charge_content')->value('data');
        return $this->fetch();
    }

    //检测收费员用户名是否存在
    public function checkStaffName(){
        if(!Db::name('core_staff')->where('username',input('username'))->find()){
            return json(['code'=>500,'msg'=>'用户名不存在']);
        }
        return json(array(['code'=>200]));
    }

    //获取要登录的收费员信息
    public function getStaffInfo(){
        if(!Db::name('core_staff')->where(['phone'=>input('post.phone'),'username'=>input('post.username')])->find()){
            return json(array('msg'=>'手机号和用户名不符!请确认是您本人手机号'));
        }
        $this->code();
        return json(200);
    }

    //忘记密码
    public function find_staff_pass(){
        if($this->request->isPost()){
            $data = input('post.');
            $validate = new Validate([
                ['username','require','请输入用户名'],
                ['phone','require','请输入手机号'],
                ['code','require','请输入验证码'],
                ['password','require','请输入密码'],
                ['password_show','require','请输入确认密码'],
            ]);
            if(!$validate->check($data)){
                return json(array('msg'=>$validate->getError()));
            }
            if($data['password'] != $data['password_show']){
                return json(array('msg'=>'两次密码不正确，请重新输入！'));
            }
            if($data['code'] != session('code') || !session('?code')){
                return json(array('msg'=>'验证码不正确，请重新填写'));
            }
            session('code',null);
            Db::name('core_staff')->where('username',$data['username'])->update(['password' => md5($data['password']),'password_show'=>$data['password_show']]);
            return json(200);
        }
        return $this->fetch();
    }

    //登出
    public function loginOut(){
        session('user_id',null);
        if(session('user_id')==""||session('user_id')==null){
            return json(200);
        }
        return json(array('msg'=>'退出失败'));
    }

    //收费员登出
    public function staffLoginOut(){
        session('staff_id',null);
        if(session('staff_id')==""||session('staff_id')==null){
            return json(200);
        }
        return json(array('msg'=>'退出失败'));
    }

    /**
     * 计算费用
     * @param $info 用户信息
     */
    protected function getPay($info){
        //费用计算
        $region = Db::name('core_region')->where('id',$info['r_pid'])->find();
        $field = $info['price_status'] == 1 ? 'price_civil' : 'price_commercial';
        if($info['stop_square']){
            $square = $info['square'] - $info['stop_square'];
        }else{
            $square = $info['square'];
        }
        //总面积费用计算
        $money = $square * $region[$field] * 6;
        //超高部分费用计算
        $proportion = $region['super_high_money'] / 100;//超高部分比例
        $super_high = $info['super_high_square'] / $region['super_high']; //超高平米
        $data['super_high_money'] = round($super_high * $region[$field] * 6 * $proportion,1);//超高部分费用
        //最终费用
        $data['price'] = round($money + $data['super_high_money'],1);
        return $data;
    }

    //已缴费数/未交费数
   public function yesOrNoCharge(){
        $this->view->yesPay = count(Db::name('core_user')->where('pay_status',1)->select());
        $this->view->noPay = count(Db::name('core_user')->where('pay_status',0)->select());
        $yesPay = count(Db::name('core_user')->where('pay_status',1)->select());
        $noPay = count(Db::name('core_user')->where('pay_status',0)->select());
        return array($yesPay,$noPay);
   }

    //生成CODE码
    public function code(){
        $code = '';
        for($i=0;$i<6;$i++){
            $code .= rand(0,9);
        }
        session('code',$code);
        $this->sendSMS('post',input('phone'),$code);
        return json(200);
    }

    /*
    * 发送短信
    * $type @string 请求方式,post或者get,推荐post,get有参数长度2048限制
    */
    function sendSMS($type='post',$phone,$code){
        $url = 'http://www.stongnet.com/sdkhttp/sendsms.aspx';      //http接口地址

        $reg_code = '101100-WEB-CSQD-116822';       //华兴软通注册码，请在这里填写您从客服那得到的注册码
        $reg_pw = 'AFKWXLXU';       //华兴软通注册码对应的密码，请在这里填写您从客服那得到的密码
        $source_add = '';       //子通道号（最长10位，可为空
        $phone = $phone;        //手机号码（最多1000个），多个用英文逗号(,)隔开，不可为空
        /*
         *  签名:工信部规定,签名表示用户的真实身份,请不要在签名中冒用别人的身份,如客户使用虚假身份我们将封号处理并以诈骗为由提交工信部备案，一切责任后果由客户承担
         *  华兴软通短信系统要求签名必须附加在短信内容的尾部,以全角中文中括号包括,且括号之后不能再有空格,否则将导致发送失败
         *  虽然在程序中,签名是附加在短信内容的尾部,但是真实短信送达到用户手机时,签名则可能出现在短信的头部,这是各地运营商的政策不同,会在它们自己的路由对签名的位置做调整
         *  短信内容的长度计算会包括签名;签名内容的长度限制受政策变化,具体请咨询客服
         *  写在程序里是让用户自定义签名的方式,还有一种方式是让客服绑定签名,这种方式签名不需要写在程序中,具体请咨询客服
         */
        $signature = '【回民中学】';
        //$code=rand(1000,9999) ;      //签名
        if(is_numeric($code)){
            $content = '回民中学提示：您的短信验证码为:' . $code .'感谢您对回民中学的支持'.$signature;
        }else{
            $content = '回民中学提示：' . $code .'感谢您对回民中学的支持'.$signature;
        }
        $param_arry = array();
        $param_arry['reg'] = $reg_code;
        $param_arry['pwd'] = $reg_pw;
        $param_arry['sourceadd'] = $source_add;
        $param_arry['phone'] = $phone;
        $param_arry['content'] = $content;

        if($type =='get'){
            $this->curlGet($url,$param_arry);
        }else{
            $this->curlPost($url,$param_arry);
        }
    }

    /**
     * 基于curl的post访问方式(推荐)
     * 要求php打开curl扩展
     * $url @string 请求地址
     * $param_array @array 参数数组
     */
    function curlPost($url,$param_array){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($param_array));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if(!empty($error)){     //curl有错误
            echo $error;
        }else{      //输出请求结果
            //echo $data;
        }
    }
}